package com.lcw.citylist;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.lcw.citylist.adapter.CityAdapter;
import com.lcw.citylist.data.CityData;
import com.lcw.citylist.model.CityItem;
import com.lcw.citylist.util.Const;
import com.lcw.citylist.widget.ContactItemInterface;
import com.lcw.citylist.widget.ContactListViewImpl;

public class ActivityCityList extends Activity implements TextWatcher, View.OnClickListener {
    private final static String TAG = ActivityCityList.class.getSimpleName();

    private Context context_ = ActivityCityList.this;

    private ContactListViewImpl listview;
    private View mHeaderView;

    private EditText searchBox;
    private String searchString;

    private Object searchLock = new Object();
    boolean inSearchMode = false;

    private List<ContactItemInterface> mAllData;
    private List<ContactItemInterface> mFilterData;

    private SearchListTask curSearchTask = null;

    private TextView mTextCity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_city_list);

        mTextCity = (TextView) findViewById(R.id.textview_city);

        mFilterData = new ArrayList<ContactItemInterface>();
        mAllData = CityData.getSampleContactList();

        CityAdapter adapter = new CityAdapter(this,
                R.layout.city_item, mAllData);

        listview = (ContactListViewImpl) findViewById(R.id.listview);
        mHeaderView = createHeaderView(listview);
        listview.addHeaderView(mHeaderView);
        listview.setFastScrollEnabled(true);
        listview.setAdapter(adapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position,
                                    long id) {
                List<ContactItemInterface> searchList;
                if (inSearchMode) {
                    searchList = mFilterData;
                } else {
                    searchList = mAllData;
                    position--;
                }
                //
                if (position < 0) {
                    //表示点击的是热门城市的空白处
                    return;
                }
                String city = searchList.get(position).getDisplayInfo();
                finishCitySelect(city);
            }
        });

        searchBox = (EditText) findViewById(R.id.input_search_query);
        searchBox.addTextChangedListener(this);

        findViewById(R.id.textview_cancel).setOnClickListener(this);

        setupData();
    }

    private void setupData() {
        String city = getIntent().getStringExtra(Const.CITY);
        if (city != null) {
            mTextCity.setText("当前城市：" + city);
        }
    }

    private View createHeaderView(ListView parent) {
        View header = LayoutInflater.from(this).inflate(R.layout.city_item_hot, parent, false);
        header.findViewById(R.id.textview_city_beijing).setOnClickListener(this);
        header.findViewById(R.id.textview_city_shanghai).setOnClickListener(this);
        header.findViewById(R.id.textview_city_guangzhou).setOnClickListener(this);
        header.findViewById(R.id.textview_city_shenzheng).setOnClickListener(this);
        header.findViewById(R.id.textview_city_chongqing).setOnClickListener(this);
        header.findViewById(R.id.textview_city_wuhan).setOnClickListener(this);
        return header;
    }

    private void finishCitySelect(String city) {
        //将数据传回去
        Intent data = new Intent();
        data.putExtra(Const.KEY_CITY, city);
        setResult(Activity.RESULT_OK, data);
        finish();
    }

    @Override
    public void afterTextChanged(Editable s) {
        searchString = searchBox.getText().toString().trim().toUpperCase();

        if (curSearchTask != null
                && curSearchTask.getStatus() != AsyncTask.Status.FINISHED) {
            try {
                curSearchTask.cancel(true);
            } catch (Exception e) {
                Log.i(TAG, "Fail to cancel running search task");
            }

        }
        curSearchTask = new SearchListTask();
        curSearchTask.execute(searchString);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // do nothing
    }

    private class SearchListTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            mFilterData.clear();

            String keyword = params[0];

            inSearchMode = (keyword.length() > 0);

            if (inSearchMode) {
                // get all the items matching this
                for (ContactItemInterface item : mAllData) {
                    CityItem contact = (CityItem) item;

                    boolean isPinyin = contact.getFullName().toUpperCase()
                            .indexOf(keyword) > -1;
                    boolean isChinese = contact.getNickName().indexOf(keyword) > -1;

                    if (isPinyin || isChinese) {
                        mFilterData.add(item);
                    }

                }

            }
            return null;
        }

        protected void onPostExecute(String result) {
            synchronized (searchLock) {
                if (inSearchMode) {
                    CityAdapter adapter = new CityAdapter(context_,
                            R.layout.city_item, mFilterData);
                    adapter.setInSearchMode(true);
                    listview.setInSearchMode(true);
                    if (mHeaderView != null) {
                        listview.removeHeaderView(mHeaderView);
                    }
                    listview.setAdapter(adapter);
                } else {
                    CityAdapter adapter = new CityAdapter(context_,
                            R.layout.city_item, mAllData);
                    adapter.setInSearchMode(false);
                    listview.setInSearchMode(false);
                    if (mHeaderView != null) {
                        listview.setAdapter(null);
                        listview.addHeaderView(mHeaderView);
                    }
                    listview.setAdapter(adapter);
                }
            }

        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.textview_city_beijing) {
            finishCitySelect("北京");

        } else if (i == R.id.textview_city_shanghai) {
            finishCitySelect("上海");

        } else if (i == R.id.textview_city_guangzhou) {
            finishCitySelect("广州");

        } else if (i == R.id.textview_city_shenzheng) {
            finishCitySelect("深圳");

        } else if (i == R.id.textview_city_chongqing) {
            finishCitySelect("重庆");

        } else if (i == R.id.textview_city_wuhan) {
            finishCitySelect("武汉");

        } else if (i == R.id.textview_cancel) {
            finish();

        }
    }

}
